import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_im_demo/http/dio.dart';
import 'package:flutter_im_demo/model/message_model.dart';
import 'package:flutter_im_demo/state/global_state.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:provider/provider.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import '../const_value.dart';
import 'friend_list_page.dart';

class AddFriendPage extends StatefulWidget {
  @override
  _AddFriendPageState createState() => _AddFriendPageState();
}

class _AddFriendPageState extends State<AddFriendPage> {
  var _textController;

  @override
  void initState() {
    super.initState();
    _textController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("添加"),
          flexibleSpace: Container(
            decoration: BoxDecoration(gradient: gradientColor),
          )),
      body: Container(
        child: Column(
          children: <Widget>[
            InkWell(
              onTap: () {
                showSearch(context: context, delegate: searchBarDelegate());
              },
              child: Container(
                height: 50.0,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    const SizedBox(width: 10.0),
                    Icon(
                      Icons.search,
                      color: Colors.grey,
                      size: iconSize,
                    ),
                    const SizedBox(width: 10.0),
                    Text(
                      "手机号",
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class searchBarDelegate extends SearchDelegate<String> {
  searchBarDelegate() {}

  final _editController = TextEditingController();

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
      onPressed: () {
        if (query.isEmpty) {
          close(context, null);
        } else {
          query = "";
          showSuggestions(context);
        }
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return FutureBuilder<Response>(
        builder: (context, result) {
          if (result.hasData) {
            final data = json.decode(result.data.toString());
            if (data["code"] == 1) {
              final map = data["data"] as Map;
              if (map.isNotEmpty) {
                String nickName = map["nickName"];
                String phone = map["phone"];
                String avatar = map["avatar"];
                String friendId = map["id"];
                return ListTile(
                  onTap: () {},
                  leading: MyCircleAvatar(
                      height: 40.0, avatar: avatar, tag: friendId),
                  title: Text(
                    nickName,
                    style:
                        TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
                  ),
                  trailing: FlatButton(
                      onPressed: () {
                        _showAlertDialog(context, friendId);
                      },
                      child: Text("添加")),
                );
              }
            }
            return Container(
              padding: EdgeInsets.only(top: 20.0),
              alignment: Alignment.topCenter,
              child: Text("该用户不存在"),
            );
          } else {
            return Container(
              width: 30.0,
              height: 30.0,
              child: SpinKitFadingCube(
                color: color3,
                size: loadingWidgetSize,
              ),
            );
          }
        },
        future: _getResult(query));
  }

  _showAlertDialog(BuildContext context, String friendId) {
    showDialog(
        // 设置点击 dialog 外部不取消 dialog，默认能够取消
        barrierDismissible: true,
        context: context,
        builder: (context) => AlertDialog(
              title: Text(
                '发送验证',
                style: TextStyle(fontSize: 16.0),
              ),
              content: TextField(
                controller: _editController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                ),
                maxLines: 4,
              ),
              shape:
                  OutlineInputBorder(borderRadius: BorderRadius.circular(10.0)),
              actions: <Widget>[
                FlatButton(
                    onPressed: () => Navigator.pop(context),
                    child: Text(
                      '关闭',
                      style: TextStyle(color: Colors.black),
                    )),
                Consumer<GlobalState>(builder: (context, state, _) {
                  return FlatButton(
                      onPressed: () =>
                          _sendAddFriendMsg(context, state, friendId),
                      child: Text('发送'));
                }),
              ],
            ));
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Container();
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    assert(context != null);
    final ThemeData theme = Theme.of(context);
    assert(theme != null);
    return theme.copyWith(
      primaryColor: Colors.white,
      primaryIconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
      primaryColorBrightness: Brightness.light,
      primaryTextTheme: theme.textTheme,
    );
  }

  Future<Response> _getResult(String query) {
    return dio.post("/$apiVersion/search", data: {"phone": query});
  }

  _sendAddFriendMsg(BuildContext context, GlobalState state, String friendId) {
    final text = _editController.text.trim();
    final body = {
      "body" : text.isEmpty ? "请求添加为好友" : text,
      "avatar" : state.userInfoModel.avatar,
      "nickName" : state.userInfoModel.nickName,
    };
    final msg = Message(
        fromId: state.userInfoModel.id,
        toId: friendId,
        body: json.encode(body),
        type: 4);
    print("_sendAdd: ${msg.toString()}");
    state.insertAddFriendMsg(msg);
    state.sendMsg(msg);
    _editController.clear();
    Navigator.pop(context);
  }
}
